import React, { useEffect, useState } from 'react'
import AppDialog from '../../components/AppDialog'
import { Form, Input, Button, Space, Cascader } from 'antd';
import Message from '../../components/Message';
import { addCategories, editCategories } from "../../api/categories";

const AddOrEditCategories = ({ visible, catInfo, parentCate, onHide }) => {
  const tailLayout = {
    wrapperCol: {
      offset: 10,
      span: 14,
    },
  };
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (visible && catInfo.cat_id) {
      const initialValues = {
        cat_name: catInfo.cat_name
      }
      form.setFieldsValue(initialValues)
    }
  }, [catInfo])

  // 点击确定
  const onFinish = async (values) => {
    setLoading(true)
    let data = {...values}
    if (!catInfo.cat_id) {
      // 如果selectedKeys数组中的length大于0，则表示选中父级分类
      // 反之就表示没有选中任何父级
      if (values.selectedKeys && values.selectedKeys.length > 0) {
        // 父级分类ID
        data.cat_pid = values.selectedKeys[values.selectedKeys.length - 1];
        // 当前分类等级
        data.cat_level = values.selectedKeys.length;
      } else {
        // 父级分类ID
        data.cat_pid = 0;
        // 当前分类等级
        data.cat_level = 0;
      }
      await addCategories(data).finally(() => {
        setLoading(false)
      });
      Message("success", "添加成功");
    } else {
      values.id = catInfo.id
      await editCategories(catInfo.cat_id, values).finally(() => {
        setLoading(false)
      });
      Message("success", "编辑成功");
    }

    handleDialogClosed('success')
  };

  // 提交表单且数据验证失败后回调事件
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  // 点击取消
  const handleDialogClosed = (type) => {
    form.resetFields();
    onHide(type)
  };

  return (visible ?
    <AppDialog
      title={catInfo.cat_id ? '编辑分类' : '添加分类'}
      visible={visible}
      onClosed={handleDialogClosed}
    >
      <Form
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item
          label="分类名称"
          name="cat_name"
          rules={[{ required: true, message: '请输入分类名称' }]}
        >
          <Input />
        </Form.Item>
        {
          !catInfo.cat_id ? 
          <Form.Item
            label="父级分类"
            name="selectedKeys"
          >
            <Cascader
              fieldNames={{
                label: 'cat_name',
                value: 'cat_id',
                children: 'children',
              }}
              options={parentCate}
              style={{ width: '100%' }}
              expandTrigger="hover"
              changeOnSelect={true}
              allowClear={true}
            />
          </Form.Item>
          : null
        }
        <Form.Item {...tailLayout}>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>确定</Button>
            <Button onClick={() => handleDialogClosed()}>取消</Button>
          </Space>
        </Form.Item>
      </Form>
    </AppDialog>
    : null
  )
}

export default AddOrEditCategories
